<?php
namespace Infinity;

use Symfony\Component\Yaml\Yaml;

class Configs {
  private $configs;
  private $current_name;

  public function __construct($configs=[]) {
    $this->configs = $configs;
  }

  /**
   * @param $name
   * @return \Infinity\Configs
   */
  public static function config($name) {
    $configs = &drupal_static(__CLASS__.'::'.__FUNCTION__, null);
    if(!isset($configs)) {
      $configs = new self();
    }
    $configs->loadYml($name);
    return $configs;
  }

  public function loadYml($name) {
    $cache_key = 'infinity.configs.'.$name;
    $cache_data = null;
    if($cached = cache_get($cache_key)) {
      $cache_data = $cached->data;
    } else {
      $names = explode('.', $name);
      $preg_name = str_replace('.', '\.', $name);
      $files = file_scan_directory(drupal_get_path('module', $names[0]), '/^'.$preg_name.'\.yml$/');
      foreach($files as $path => $file) {
        $cache_data = Yaml::parse(file_get_contents($path));
      }
      cache_set($cache_key, $cache_data);
    }
    $this->configs[$name] = $cache_data;

    $this->current_name = $name;
  }

  /**
   * @param null $key
   * @param null $default
   * @return array
   */
  public function get($key=null, $default=null) {
    if($key) {
      if(!empty($this->configs[$this->current_name][$key]))
        return $this->configs[$this->current_name][$key];
    }
    if(!empty($this->configs[$this->current_name]))
      return $this->configs[$this->current_name];
    return variable_get("{$this->current_name}.$key", $default);
  }
}
/*
Infinity\Configs::config('node.settings')->get('pager');
*/